package com.asianfo.dao.meta;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;

import com.asiainfo.simpledao.JdbcUtil;

/**
 * SQL元数据加载
 */
public class SqlMetaDataHelper {

	public Collection<TableMetaData> loadingAllTableMetaData(Connection conn, String catalog, String schema, String namePattern) throws SQLException {
		ResultSet rs = null;
		try {
			Collection<TableMetaData> tmds = new HashSet<TableMetaData>();
			DatabaseMetaData dbmd = conn.getMetaData();
			rs = dbmd.getTables(catalog, schema, namePattern, new String[] { "TABLE", "VIEW" });
			while (rs.next()) {
				TableMetaData tableMetaData = new TableMetaData(schema, catalog);
				tableMetaData.setName(rs.getString("TABLE_NAME"));
				tableMetaData.setRemarks(rs.getString("REMARKS"));
				tmds.add(tableMetaData);
			}
			return tmds;
		} catch (SQLException e) {
			throw e;
		} finally {
			JdbcUtil.close(rs);
		}
	}

	public Collection<ColumnMetaData> loadingAllColumnMetaData(Connection conn, TableMetaData tableMetaData) throws SQLException {
		ResultSet rs = null;
		try {
			DatabaseMetaData dbmd = conn.getMetaData();
			rs = dbmd.getPrimaryKeys(tableMetaData.getCatalog(), tableMetaData.getSchema(), tableMetaData.getName());
			while (rs.next()) {
				String idName = rs.getString("COLUMN_NAME");
				tableMetaData.addIdName(idName);
			}
			rs = dbmd.getPrimaryKeys(tableMetaData.getCatalog(), tableMetaData.getSchema(), "%");
			while (rs.next()) {
				String colName = rs.getString("COLUMN_NAME");
				Integer sqlType = rs.getInt("DATA_TYPE");
				Integer size = rs.getInt("COLUMN_SIZE");
				Object o = rs.getObject("DECIMAL_DIGITS");
				Integer digit = null;
				if (o != null) {
					digit = ((Number) o).intValue();
				}
				String remark = rs.getString("REMARKS");
				tableMetaData.addColumnMetaData(new ColumnMetaData());
			}
		} catch (Exception e) {
			throw e;
		} finally {
			JdbcUtil.close(rs);
		}
		return null;
	}

}
